﻿using System;
using System.Net.Sockets;
using System.Threading;

namespace UDFSocket
{
    /// <summary>
    /// 异步读状态对象
    /// </summary>
    internal class AsyncReadStateObject
    {
        public ManualResetEvent eventDone;
        public byte[] buffer;
        public Exception exception;
        public Int32 numberOfBytesRead;
        public SocketPlus workScoket;
    }

    /// <summary>
    /// 实现TcpClient的异步接收
    /// </summary>
    public partial class SocketPlus
    {
        /// <summary>
        /// 设置读超时等待值
        /// </summary>
        public Int32 ReadTimeout = Timeout.Infinite;

        /// <summary>
        /// 异步接收
        /// </summary>
        /// <param name="data">接收到的字节数组</param>
        public void Read( out Byte[] data)
        {
            // 获取网络数据流
            //NetworkStream netStream = GetStream();

            // 用户定义对象
            AsyncReadStateObject State = new AsyncReadStateObject
            {   // 将事件状态设置为非终止状态，导致线程阻止
                eventDone = new ManualResetEvent(false),
                buffer = new byte[1024],
                exception = null,
                numberOfBytesRead = -1,
                workScoket = this
            };

            Byte[] Buffer = new Byte[ReceiveBufferSize];

            //Int32 TotalBytes = 0;       // 总共需要接收的字节数
            //Int32 ReceivedBytes = 0;    // 当前已接收的字节数
            while (true)
            {
                // 将事件状态设置为非终止状态，导致线程阻止
                State.eventDone.Reset();

                // 异步读取网络数据流
                BeginReceive(State.buffer,
                    0,
                    State.buffer.Length,
                    SocketFlags.None,
                    new AsyncCallback(AsyncReadCallback),
                    State);
                // 等待操作完成信号
                if (State.eventDone.WaitOne(ReadTimeout, false))
                {   // 接收到信号
                    if (State.exception != null)
                    {
                        throw State.exception;
                    }
                    // 连接已经断开
                    if (State.numberOfBytesRead == 0)
                    {
                        throw new SocketException();
                    }
                    #region

                    //数据读取完成
                    //else if (State.numberOfBytesRead > 0)
                    //{
                    //    if (TotalBytes == 0)
                    //    {   // 提取流头部字节长度信息
                    //        TotalBytes = BitConverter.ToInt32(Buffer, 0);

                    //        // 保存剩余信息
                    //        //memStream.Write(Buffer, 4, State.numberOfBytesRead - 4);
                    //    }
                    //    else
                    //    {
                    //        //memStream.Write(Buffer, 0, State.numberOfBytesRead);
                    //    }
                    //    ReceivedBytes += State.numberOfBytesRead;
                    //    if (ReceivedBytes >= TotalBytes) break;
                    //}

                    
                    //else
                    //{   // 超时异常
                    //    throw new TimeoutException();
                    //}

                    #endregion
                }
            }
        }
        /// <summary>
        /// 异步读取回调函数
        /// </summary>
        /// <param name="ar">异步操作结果</param>
        private static void AsyncReadCallback(IAsyncResult ar)
        {
            AsyncReadStateObject State = ar.AsyncState as AsyncReadStateObject;
            // 异步写入结束
            try
            {   
                State.numberOfBytesRead = State.workScoket.EndReceive(ar);
            }
            // 异步连接异常
            catch (Exception e)
            {   
                State.exception = e;
            }
            // 将事件状态设置为终止状态，线程继续
            finally
            {   
                State.eventDone.Set();
            }
        }
    }
}
